package com.rabincorp.tactile.feed;

import com.rabincorp.tactile.entity.YahooFeedItem;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author irabin
 */
public class YahooFeed {

    private static YahooFeed instance = null;

    public static YahooFeed getInstance() {
        if (instance == null) {
            instance = new YahooFeed();
        }

        return instance;
    }

    @SuppressWarnings("unchecked")
    public List<YahooFeedItem> parse(String feedURL) {

        List<YahooFeedItem> newsItems = new ArrayList<YahooFeedItem>();

        try {
            URL url = new URL(feedURL);

            FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
            FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);

            SyndFeed feed = fetcher.retrieveFeed(url);
            
            List<SyndEntry> entries = (List<SyndEntry>) feed.getEntries();
            for (SyndEntry entry : entries) {

                YahooFeedItem news = new YahooFeedItem();

                news.setGuid(entry.getUri());
                news.setTitle(entry.getTitle());
                news.setLink(entry.getLink());
                news.setPubDate(entry.getPublishedDate());
                news.setDescription(entry.getDescription().getValue());
                
                newsItems.add(news);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FeedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FetcherException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return newsItems;
    }
}
